package com.eling.elcms.system.webapp.controller;

import com.eling.elcms.core.AppContext;
import com.eling.elcms.core.exception.BusinessException;
import com.eling.elcms.core.webapp.controller.BaseFormController;
import com.eling.elcms.core.webapp.spring.ModelFilling;
import com.eling.elcms.privilege.model.Role;
import com.eling.elcms.privilege.model.User;
import com.eling.elcms.privilege.service.IRoleManager;
import com.eling.elcms.privilege.service.IUserManager;
import com.eling.elcms.system.model.ElcmsUser;
import com.eling.elcms.system.service.IElcmsUserManager;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
public class ElcmsUserController extends BaseFormController {

    @Autowired
    private IUserManager userManager;

    @Autowired
    private IElcmsUserManager elcmsUserManager;

    @Autowired
    private IRoleManager roleManager;
    
    @RequestMapping("/api/user/add*")
    @ResponseBody
	public User save(@ModelAttribute("user")@ModelFilling ElcmsUser user) {
    	if (CollectionUtils.isEmpty(user.getRoles())) {
        	User me = AppContext.curUser();
        	if (userManager.isSuperAdmin(me.getPkUser()) && null == user.getPkUser()) {
        		// 如果是后台管理员，则新增的用户都是机构管理员角色
        		Set<Role> roles = new HashSet<Role>();
        		roles.add(roleManager.get(Role.ROLE_DEPARTMENT));
        		user.setRoles(roles);
        	} else {
        		throw new BusinessException("没有为用户指定角色");
        	}
    	}

        return elcmsUserManager.save(user);
    }
    
    
    @RequestMapping("/api/elcmsuser/query")
    @ResponseBody
    public List<ElcmsUser> query(ElcmsUser cond) {
    	return elcmsUserManager.query(cond);
    }
    
    @RequestMapping("/api/user/building")
    @ResponseBody
    public List<ElcmsUser> queryByBuilding(@RequestParam(value = "pkBuilding") Long pkBuilding, @RequestParam(value = "pkRole") Long pkRole) {
    	return elcmsUserManager.queryUsersByBuilding(pkBuilding, pkRole);
    }  

}
